# -*- coding: utf-8 -*-

from flask import render_template, redirect, url_for, request, jsonify
from flask_login import login_user, logout_user, current_user, login_required

from . import auth
from .models import User
import traceback


@auth.route('/login', methods=['GET', 'POST'])
def login():
    if request.method == 'POST':
        form_data = request.get_json()
        username = form_data.get('username')
        password = form_data.get('password')
        user = User.query.filter(User.username == username).first()
        if user is None or not user.verify_password(password):
            return jsonify({'message': 'invalid username or password'}), 403
        login_user(user)
        return jsonify({})
    else:
        if current_user.is_authenticated:
            return redirect(url_for('manager.gamesets'))
        return render_template('auth/login.html')


@auth.route('/logout')
@login_required
def logout():
    logout_user()
    return redirect(url_for('manager.gamesets'))
